package xyz.myachin.saveto.ui.settings

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import xyz.myachin.saveto.R
import xyz.myachin.saveto.logic.intent.*
import xyz.myachin.saveto.settings.Settings
import xyz.myachin.saveto.ui.supports.AskDirAccessActivity

class MimeTypesSettingsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.settings_activity)
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings, SettingsFragment())
                .commit()
        }
        supportActionBar?.setDisplayShowHomeEnabled(true)
    }

    class SettingsFragment : PreferenceFragmentCompat() {
        private var setDocumentPref: Preference? = null
        private var forgetDocumentPref: Preference? = null

        private var setArchivePref: Preference? = null
        private var forgetArchivePref: Preference? = null

        private var setImagePref: Preference? = null
        private var forgetImagePref: Preference? = null

        private var setVideoPref: Preference? = null
        private var forgetVideoPref: Preference? = null

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.mime_type_preferences, rootKey)

            setPrefs()
            findDisablingPrefs()
        }


        private fun setPrefs() {
            findPreference<Preference>(getString(R.string.select_doc_dir_key))?.apply {
                setDocumentPref = this
                onPreferenceClickListener = setOnClickListener(ACCESS_DOCUMENTS_CODE)
                setPrefText(this, Settings.documentUri)
            }

            findPreference<Preference>(getString(R.string.select_archive_dir_key))?.apply {
                setArchivePref = this
                onPreferenceClickListener = setOnClickListener(ACCESS_ARCHIVES_CODE)
                setPrefText(this, Settings.archiveUri)
            }

            findPreference<Preference>(getString(R.string.select_image_dir_key))?.apply {
                setImagePref = this
                onPreferenceClickListener = setOnClickListener(ACCESS_IMAGES_CODE)
                setPrefText(this, Settings.imageUri)
            }

            findPreference<Preference>(getString(R.string.select_video_dir_key))?.apply {
                setVideoPref = this
                onPreferenceClickListener = setOnClickListener(ACCESS_VIDEOS_CODE)
                setPrefText(this, Settings.videoUri)
            }
        }

        private fun setOnClickListener(accessCode: Int): Preference.OnPreferenceClickListener {
            return Preference.OnPreferenceClickListener {
                val intent = Intent(requireContext(), AskDirAccessActivity::class.java)
                    .putExtra(EXTRA_DIRECTORY_ACCESS_NEED, accessCode)

                try {
                    startActivityForResult(intent, accessCode)
                    true
                } catch (_: ActivityNotFoundException) {
                    false
                }
            }
        }

        private fun findDisablingPrefs() {
            findPreference<Preference>(getString(R.string.forget_docs))?.apply {
                forgetDocumentPref = this
                onPreferenceClickListener = Preference.OnPreferenceClickListener {
                    it.isVisible = false
                    Settings.documentUri = null
                    setPrefText(setDocumentPref, null)
                    true
                }
                if (Settings.documentUri != null) this.isVisible = true
            }

            findPreference<Preference>(getString(R.string.forget_archives))?.apply {
                forgetArchivePref = this
                onPreferenceClickListener = Preference.OnPreferenceClickListener {
                    it.isVisible = false
                    Settings.archiveUri = null
                    setPrefText(setArchivePref, null)
                    true
                }
                if (Settings.archiveUri != null) this.isVisible = true
            }

            findPreference<Preference>(getString(R.string.forget_images))?.apply {
                forgetImagePref = this
                onPreferenceClickListener = Preference.OnPreferenceClickListener {
                    it.isVisible = false
                    Settings.imageUri = null
                    setPrefText(setImagePref, null)
                    true
                }
                if (Settings.imageUri != null) this.isVisible = true
            }

            findPreference<Preference>(getString(R.string.forget_videos))?.apply {
                forgetVideoPref = this
                onPreferenceClickListener = Preference.OnPreferenceClickListener {
                    it.isVisible = false
                    Settings.videoUri = null
                    setPrefText(setVideoPref, null)
                    true
                }
                if (Settings.videoUri != null) this.isVisible = true
            }
        }

        private fun setPrefText(pref: Preference?, uri: Uri?) {
            if (uri != null) {
                pref?.title = getString(R.string.change_change_folder)
                return
            }
            pref?.title = getString(R.string.select_directory_title)
        }

        @Deprecated("Deprecated in Java")
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
            if (resultCode == RESULT_OK) {
                when (requestCode) {
                    ACCESS_DOCUMENTS_CODE -> {
                        setPrefText(setDocumentPref, Settings.documentUri)
                        forgetDocumentPref?.isVisible = true
                    }
                    ACCESS_ARCHIVES_CODE -> {
                        setPrefText(setArchivePref, Settings.archiveUri)
                        forgetArchivePref?.isVisible = true
                    }
                    ACCESS_IMAGES_CODE -> {
                        setPrefText(setImagePref, Settings.imageUri)
                        forgetImagePref?.isVisible = true
                    }
                    ACCESS_VIDEOS_CODE -> {
                        setPrefText(setVideoPref, Settings.videoUri)
                        forgetVideoPref?.isVisible = true
                    }
                }
            }
        }
    }
}